/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.*;
import me.zhengjie.repository.*;
import me.zhengjie.service.FzAllSizeService;
import me.zhengjie.service.dto.FzAllSizeDto;
import me.zhengjie.service.dto.FzAllSizeQueryCriteria;
import me.zhengjie.service.mapstruct.FzAllSizeMapper;
import me.zhengjie.service.mapstruct.FzOrdersMapper;
import me.zhengjie.util.FileUtils;
import me.zhengjie.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zcc
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-07-03
 **/
@Service
@RequiredArgsConstructor
public class FzAllSizeServiceImpl implements FzAllSizeService {

    private final FzAllSizeRepository fzAllSizeRepository;
    private final FzAllSizeMapper fzAllSizeMapper;
    private final AllsizeTechnologyRepository allsizeTechnologyRepository;
    private final FzFilesRepository fzFilesRepository;
    private final FzChunkRepository fzChunkRepository;
    private final FzSamplesServiceImpl samplesService;

    private final FzOrdersRepository fzOrdersRepository;
    private final OrderTechnologyRepository orderTechnologyRepository;

    @Value("${file.windows.path}")
    private String uploadFolder;

    @Override
    public Map<String, Object> queryAll(FzAllSizeQueryCriteria criteria, Pageable pageable) {
        Page<FzAllSize> page = fzAllSizeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(fzAllSizeMapper::toDto));
    }

    @Override
    public List<FzAllSizeDto> queryAll(FzAllSizeQueryCriteria criteria) {
        return fzAllSizeMapper.toDto(fzAllSizeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public FzAllSizeDto findById(String asId) {
        FzAllSize fzAllSize = fzAllSizeRepository.findById(asId).orElseGet(FzAllSize::new);
        ValidationUtil.isNull(fzAllSize.getAsId(), "FzAllSize", "asId", asId);
        return fzAllSizeMapper.toDto(fzAllSize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FzAllSizeDto create(FzAllSize resources) {
//        resources.setAsId(IdUtil.simpleUUID());
        return fzAllSizeMapper.toDto(fzAllSizeRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(FzAllSize resources) {
        FzAllSize fzAllSize = fzAllSizeRepository.findById(resources.getAsId()).orElseGet(FzAllSize::new);
        ValidationUtil.isNull(fzAllSize.getAsId(), "FzAllSize", "id", resources.getAsId());
        fzAllSize.copy(resources);
        fzAllSizeRepository.save(fzAllSize);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String asId : ids) {
            fzAllSizeRepository.deleteById(asId);
            List<AllsizeTechnology> list = allsizeTechnologyRepository.findByAsId(asId);
            allsizeTechnologyRepository.deleteAll(list);

            List<ErpFiles> files = fzFilesRepository.findBybid(asId);
            fzFilesRepository.deleteAll(files);

            List<ErpChunk> chunks = fzChunkRepository.findBybid(asId);
            fzChunkRepository.deleteAll(chunks);

            String sourcePath = uploadFolder + SecurityUtils.getCurrentUsername() + File.separator + asId;
            FileUtils.deleteDir(new File(sourcePath));
        }
    }

    @Override
    public void download(List<FzAllSizeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FzAllSizeDto allSizeDto : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("文件名称", allSizeDto.getFileName());
            map.put("日期", allSizeDto.getDateTime());
            map.put("客户", allSizeDto.getCustomer());
            map.put("类别", allSizeDto.getTypes());
            map.put("菲林", allSizeDto.getFeilin());
            map.put("模具", allSizeDto.getModel());
            map.put("备注", allSizeDto.getRemark());
            map.put("针数", allSizeDto.getNeedleNum());
            map.put("行数", allSizeDto.getSampleRows());
            map.put("单片时间", allSizeDto.getSingleChipTime());
            map.put("单片重量", allSizeDto.getWeight());
            map.put("烫机温度", allSizeDto.getScaldTemp());
            map.put("烫机速度", allSizeDto.getScaldSpeed());
            map.put("烫机压力", allSizeDto.getScaldPre());
            map.put("样品工艺", allSizeDto.getAllsizeTechnologyId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyTo(String bid, String type) throws IOException {
        FzAllSize allSize = fzAllSizeRepository.findById(bid).orElseGet(FzAllSize::new);
        String newSid = IdUtil.simpleUUID();
        List<AllsizeTechnology> technologies = allsizeTechnologyRepository.findByAsId(bid);
        if ("order".equals(type)) {
            List<OrderTechnology> newTechs = new ArrayList<>();
            for (AllsizeTechnology technology : technologies) {
                OrderTechnology newsame = new OrderTechnology();
                technology.copyTo(newsame);
                newsame.setTechId(IdUtil.simpleUUID());
                newsame.setOid(newSid);

                newTechs.add(newsame);
            }
            orderTechnologyRepository.saveAll(newTechs);

            FzOrders newOrder = new FzOrders();
            allSize.copyTo(newOrder);
            newOrder.setOrderId(newSid);
            newOrder.setOrderTechnologyId(newTechs.stream().map(OrderTechnology::getTechId).collect(Collectors.joining(",")));
            fzOrdersRepository.save(newOrder);
        }

        samplesService.copyAttach(newSid, bid, type);

        return true;
    }
}